#include "kpextMemoryResource.h"

#define BOOLBA_TO_INT(B, A) ((static_cast<uint32_t>(B) << 1) | static_cast<uint32_t>(A))

using namespace kpext;

StagingBuffer::StagingBuffer(std::shared_ptr<kpext::RawBuffer> buf,
                             std::shared_ptr<kpext::RawDeviceMemory> mem,
                             size_t size,
                             bool coherent,
                             bool cached
                             ):
    BaseBuffer(buf, mem, size, BufUsage, BufMemProp[BOOLBA_TO_INT(cached, coherent)])
{
    this->m_size = size;
    if(m_bufobj && m_memory){
        rebuild(m_bufobj, m_memory, size);
    }
    /*else{
        SPDLOG_ERROR("Construct StagingBuffer with null pointer");
        throw std::runtime_error("Invoke " __FUNCTION__ "with null pointer");
    }*/
}

StagingBuffer::~StagingBuffer()
{
    unmap();
}

void *StagingBuffer::map()
{
    if(m_memory){
        return m_memory->mapToHostMemory();
    }else{
        return nullptr;
    }
}

void StagingBuffer::unmap()
{
    if(m_memory){
        m_memory->unmapFromHostMemory();
    }
}

void StagingBuffer::flushMapped(size_t size, size_t offset)
{
    if(m_memory){
        m_memory->flushMapped(size, offset);
    }
}

void StagingBuffer::invalidateMapped(size_t size, size_t offset)
{
    if(m_memory){
        m_memory->invalidateMapped(size, offset);
    }
}
